package com.bauer.base.thread;

import java.util.concurrent.CountDownLatch;

/***
 * 用法一判断所有线程是否执行完
 */
public class CountDownLatchDemo {

    /**
     * 此方法采用join的方式实现   join采用的是wait的方式实现的  JDK不推荐在线程实例上使用wait，notify和notifyAll方法  具体原因待研究
     */
    public static void demo1(){

        Thread thread1 =  new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 finished");
            }
        });

        Thread thread2 =  new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2 finished");
            }
        });

        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("All Finished");
    }

    /**
     * 此方法采用了countDownLatch实现的  CountDownLatch的await会阻塞当前线程，直到N变成零，不一定多个线程也可以是多个点
     */
    public static void demo2(){
        final CountDownLatch  countDownLatch =  new CountDownLatch(3);
        Thread thread1 =  new Thread(new Runnable() {
            @Override
            public void run() {
                countDownLatch.countDown();
                System.out.println("thread1 finished");
                countDownLatch.countDown();
            }
        });

        Thread thread2 =  new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("thread2 finished");
                countDownLatch.countDown();
            }
        });

        thread1.start();
        thread2.start();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("All Finished  CountDownLatch");
    }

    public static void main(String[] args) {
//        demo1();
        demo2();
    }
}
